package com.penghaonan.appframework.utils;

import com.google.gson.Gson;
import com.google.gson.JsonElement;

import java.lang.reflect.Type;

public class GsonHelper {
    private static Gson gson;

    private static Gson gson() {
        if (gson == null) {
            gson = new Gson();
        }
        return gson;
    }

    public static void registerTypeAdapter(Type type, Object typeAdapter) {
        gson = gson().newBuilder().registerTypeAdapter(type, typeAdapter).create();
    }

    public static <T> T fromJson(String json, Class<T> classOfT) {
        try {
            return gson().fromJson(json, classOfT);
        } catch (Exception e) {
            Logger.e(e);
            return null;
        }
    }

    public static <T> T fromJson(String json, Type type) {
        return gson().fromJson(json, type);
    }

    public static <T> T fromJson(JsonElement jsonElement, Type typeOfT) {
        return gson().fromJson(jsonElement, typeOfT);
    }

    public static <T> T fromJson(JsonElement jsonElement, Class<T> classOfT) {
        return gson().fromJson(jsonElement, classOfT);
    }

    public static String toJson(Object src) {
        return gson().toJson(src);
    }

    public static String toJson(Object src, Type cls) {
        return gson().toJson(src, cls);
    }

    public static JsonElement toElement(Object src) {
        return gson().toJsonTree(src);
    }

    public static <T> T copy(T src) {
        try {
            return (T) fromJson(toJson(src), Class.forName(src.getClass().getName()));
        } catch (ClassNotFoundException e) {
            return null;
        }
    }
}
